package com.example.back.util;

import jakarta.servlet.http.HttpServletRequest;

public class IpUtil {

    public static String getClientIpAddress(HttpServletRequest request) {
        // 尝试从 X-Forwarded-For 获取
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (isValidIp(xForwardedFor)) {
            // 多 IP 时取第一个有效 IP
            return xForwardedFor.split(",")[0].trim();
        }

        // 尝试从 X-Real-IP 获取
        String xRealIp = request.getHeader("X-Real-IP");
        if (isValidIp(xRealIp)) {
            return xRealIp;
        }

        // 直接获取 RemoteAddr（最后备用）
        return request.getRemoteAddr();
    }

    private static boolean isValidIp(String ip) {
        return ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip);
    }
}